import axios from 'axios'
import qs from 'qs'

// const baseURL = window.location.host.split('.')[0].match('hplqytest')
//   ? 'http://hplqytest.suoluomei.cn/index.php?s=/Neikan/index'
//   : 'http://hplqytest.suoluomei.cn/index.php?s=/Neikan/index'

// 基础配置
if (process.env.NODE_ENV === 'production') {
  axios.defaults.baseURL =
  'http://jyhpay.herbsexcolor.com/index.php?s=Weixin/api/'
} else {
  axios.defaults.baseURL = '/proxy/'
}

axios.defaults.headers.post['Content-Type'] =
  'application/x-www-form-urlencoded;charset=UTF-8'
axios.defaults.timeout = 10000

let cancel
const promiseArr = {}
const CancelToken = axios.CancelToken

axios.interceptors.request.use(
  config => {
    // loading
    // 发起请求时，取消掉当前正在进行的相同请求
    if (promiseArr[config.url]) {
      // promiseArr[config.url]('操作取消')
      promiseArr[config.url] = cancel
    } else {
      promiseArr[config.url] = cancel
    }

    return config
  },
  error => {
    return Promise.reject(error)
  }
)

axios.interceptors.response.use(
  response => {
    return response
  },
  error => {
    return Promise.resolve(error.response)
  }
)

function checkStatus (response) {
  // loading
  // 如果http状态码正常，则直接返回数据
  if (
    response &&
    (response.status === 200 ||
      response.status === 304 ||
      response.status === 400)
  ) {
    return response
    // 如果不需要除了data之外的数据，可以直接 return response.data
  }
  // 异常状态下，把错误信息返回去
  return {
    status: -404,
    msg: '网络异常'
  }
}

function checkCode (res) {
  // 如果code异常(这里已经包括网络错误，服务器错误，后端抛出的错误)，可以弹出一个错误提示，告诉用户
  if (res.status === -404) {
    console.warn(res.msg)
  }

  return res
}

export default {
  post (url, data) {
    return axios({
      method: 'post',
      url,
      data: qs.stringify(data),
      cancelToken: new CancelToken(c => {
        cancel = c
      })
    })
      .then(response => {
        return checkStatus(response)
      })
      .then(res => {
        return checkCode(res)
      })
  },
  postFormdata (url, data) {
    return axios({
      method: 'post',
      url,
      data,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
      .then(response => {
        return checkStatus(response)
      })
      .then(res => {
        return checkCode(res)
      })
  },
  get (url, query) {
    return axios({
      method: 'get',
      url,
      query,
      cancelToken: new CancelToken(c => {
        cancel = c
      })
    })
      .then(response => {
        return checkStatus(response)
      })
      .then(res => {
        return checkCode(res)
      })
  }
}
